#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_pUi(new Ui::MainWindow)
{
    //设置主窗口
    m_pUi->setupUi(this);
    resize(1920, 1080);  //设置窗口大小
    setMinimumSize(960,540); //设置最小窗口
    setWindowTitle("有道云笔记");
    setWindowIcon(QIcon(":/icon/note.ico")); //设置程序图标

    //设置QWebEngineView
    m_pView = new WebEngineView(this);  //初始化m_pView
    m_pView->load(QUrl::fromUserInput(this->m_site)); //加载网址
    m_pView->settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
    setCentralWidget(m_pView); //将视图部件设置为主窗口的中心部件
    ConfigHelper config( m_configPath );

    this->m_zoomScale = config.readFromFile(m_zoomKey).toDouble();
    if( 0 == this->m_zoomScale )
        this->m_zoomScale = 1;
    this->m_pView->setZoomFactor(this->m_zoomScale); //设置放大比率

    //设置边距
//    this->m_pLayout = new QVBoxLayout(this);
//    this->m_pLayout->addWidget(this->m_pView);
//    this->m_pLayout->setMargin(0);  //设置边距为0

    //绑定快捷键
    m_pEscAct = new QAction(this);
    m_pEscAct->setShortcut(QKeySequence("Esc")); //设置快捷键,Esc为退出全屏

    m_pLookup = new QAction(this);
    m_pLookup->setShortcut(QKeySequence("Ctrl+F")); //查找功能

    m_pResetZoom = new QAction(this);
    m_pResetZoom->setShortcut(QKeySequence("Ctrl+R"));
    //将Esc快捷键与onExitFullScreen函数连接
    connect(m_pEscAct, &QAction::triggered, this, &MainWindow::onExitFullScreen);
    connect(m_pResetZoom, &QAction::triggered, this, &MainWindow::onResetZoom);
    connect(m_pLookup, &QAction::triggered, this, &MainWindow::onFindText);

    m_pView->addAction(m_pEscAct);
    m_pView->addAction(m_pResetZoom);
    m_pView->addAction(m_pLookup);

    //网页内查找功能
    this->m_pFindEdit = new QLineEdit(this);
    this->m_pFindEdit->setMaximumWidth(150);
    this->m_pUi->mainToolBar->addWidget(m_pFindEdit);

    //查找按钮
    this->m_pButton = new QToolButton(this);
    m_pButton->setText(tr("查找"));
    m_pButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    m_pButton->setStyleSheet("QToolButton{border: none; background: rgb(220, 220, 220); color: rgb(0, 0, 0);}");
    this->m_pUi->mainToolBar->addWidget(m_pButton);
    //与FindEdit进行信号连接
    connect(m_pButton, SIGNAL(clicked()), this, SLOT(clickButton()));
    //QLineEdit与m_pButton的信号绑定
    connect(m_pFindEdit,SIGNAL(returnPressed()), this, SLOT(clickButton()));

    //设置toolbar背景色
    this->m_pUi->mainToolBar->setStyleSheet("QToolBar {background: rgb(248, 248, 255)}");
    this->m_pUi->mainToolBar->hide();

    //去除状态栏
    this->statusBar()->hide();

    //挂载下载信号
    connect(m_pView->page()->profile(),SIGNAL(downloadRequested(QWebEngineDownloadItem*)),this,SLOT(downloadRequested(QWebEngineDownloadItem*)));
}

MainWindow::~MainWindow()
{
    delete m_pUi;
    delete m_pView;
    delete m_pSysTrayIcon;
    delete m_pMenu;
    delete m_pShowMainAction;
    delete m_pExitAppAction;
    delete m_pEscAct;
    delete m_pResetZoom;
    delete m_pLayout;
    delete m_pLookup;
    delete m_pFindEdit;
    delete m_pButton;
}

void MainWindow::onFullScreen()
{
    this->showFullScreen();
}

void MainWindow::onExitFullScreen()
{
    this->showMinimized(); //按ESC键退出全屏显示最小视图
}

void MainWindow::onResetZoom()
{
    this->m_pView->setZoomFactor(1);
}

void MainWindow::onFindText()
{
    m_pFindEdit->clear(); //每次清除文本框内的文字
    if( m_isHide == false )
    {
        m_isHide = true;
        this->m_pUi->mainToolBar->show();
        this->m_pFindEdit->setFocus();
    }
    else
    {
        m_isHide = false;
        this->m_pUi->mainToolBar->hide();
    }
}

void MainWindow::createActions()
{
    //设置按钮Show
    this->m_pShowMainAction = new QAction(QString("Show"),this);
    //将Show按钮连接on_showMainAction事件
    connect(m_pShowMainAction,
            SIGNAL(triggered()),
            this,
            SLOT(on_showMainAction()));
    //设置按钮Exit
    this->m_pExitAppAction = new QAction(QString("Exit"),this);
    //将Exit按钮和on_exitAppAction事件
    connect(m_pExitAppAction,
            SIGNAL(triggered()),
            this,
            SLOT(on_exitAppAction()));
}

void MainWindow::createMenu()
{
    if( nullptr == this->m_pExitAppAction )
        return;

    this->m_pMenu = new QMenu(this);
    this->m_pMenu->addAction(this->m_pShowMainAction); //增加菜单项Show按钮
    this->m_pMenu->addSeparator();                     //增加分隔符
    this->m_pMenu->addAction(this->m_pExitAppAction);  //增加菜单项Exit
    this->m_pSysTrayIcon->setContextMenu(this->m_pMenu);
}

WebEngineView *MainWindow::createView()
{
    return this->m_pView;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    event->ignore(); //忽略关闭事件
    this->hide();    //隐藏窗口
    if(  0 == this->m_flag ) //0为没有创建托盘，1为已经创建托盘
    {
        this->m_flag = 1;
        this->m_pSysTrayIcon = new QSystemTrayIcon(this); //创建托盘
        QIcon icon = QIcon(":/icon/tuopan.png"); //设置托盘的图标文件
        this->m_pSysTrayIcon->setIcon(icon);
        connect(this->m_pSysTrayIcon,
                SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                this,
                SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));


        //创建托盘操作图标
        createActions();
        createMenu();
        //在系统托盘显示此对象
        this->m_pSysTrayIcon->show();
    }
    else //如果已经创建了托盘，直接显示
    {
        this->m_pSysTrayIcon->show();
    }

}

void MainWindow::on_showMainAction()
{
    this->show();
}

void MainWindow::on_exitAppAction()
{
    ConfigHelper config(m_configPath);
    config.writeToFile( m_zoomKey ,this->m_pView->zoomFactor());
    exit(0);
}

void MainWindow::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
    switch( reason )
    {
    case QSystemTrayIcon::Trigger:
        break;
    case QSystemTrayIcon::DoubleClick:
        this->show(); //显示主窗口
        break;
    default:
        break;
    }
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    this->m_pView->resize(this->size());
}

void MainWindow::wheelEvent(QWheelEvent *event)
{
    if( event->delta() > 0 )
    {
        if( QApplication::keyboardModifiers () == Qt::CTRL )
        {
            int numDegrees = event->delta() / 8; //滚动的角度，*8就是鼠标滚动的距离
            int numSteps = numDegrees / 15;      //滚动的步数，*15就是鼠标滚动的角度
            if( numSteps > 0 )
            {
                this->m_pView->setZoomFactor(this->m_pView->zoomFactor() + 0.1 );
            }
        }
    }
    else
    {
        if( QApplication::keyboardModifiers () == Qt::CTRL )
        {
            int numDegrees = event->delta() / 8; //滚动的角度，*8就是鼠标滚动的距离
            int numSteps = numDegrees / 15;      //滚动的步数，*15就是鼠标滚动的角度
            if( numSteps < 0 )
            {
                this->m_pView->setZoomFactor(this->m_pView->zoomFactor() - 0.1 );

            }
        }
    }
}

void MainWindow::clickButton()
{
    std::this_thread::sleep_for(std::chrono::microseconds(50));
    this->m_pView->findText(m_pFindEdit->text());
}

void MainWindow::downloadRequested(QWebEngineDownloadItem *download)
{

    Q_ASSERT(download && download->state() == QWebEngineDownloadItem::DownloadRequested);

    QString path = QFileDialog::getSaveFileName(this, tr("Save as"), download->path());
    if ( path.isEmpty() )
        return;

    download->setPath(path);
    download->accept();

    show();
    //connect(download, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(setCurrentProgress(qint64, qint64)));
}
